﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net.Core;
using Wintellect.PowerCollections;
using System.Threading;
using System.Diagnostics;
using System.Globalization;

namespace NHTrace
{
  public class Logger
  {
    public Logger(NHTraceManager manager, int logCharSize)
    {
      _logCharSize = logCharSize;
      _manager = manager;
    }

    private NHTraceManager _manager;
    private int _logCharSize;

    public void LogEvents(IList<LogMessage> events)
    {
      if (_manager.LogEnabled)
      {
        try
        {
          bool newMessagesAdded = false;
          foreach (var ev in events)
          {
            while (_logCharSize < _manager.MessagesSize)
            {
              while ((_logCharSize < _manager.MessagesSize) /*&& (_manager.FirstElementHasMessages())*/)
                _manager.RemoveFirstMessage();
            }

            LogMessage ev2;
            if (_manager.ShowProcessName)
            {
              ev2 = LogMessage.Clone(ev);
              ev2.Message = String.Format("[{0}] {1}", ev.ApplicationName, ev.Message);
            }
            else
              ev2 = ev;

            _manager.AddMessage(ev2);
            newMessagesAdded = true;
          }

          if (newMessagesAdded)
          {
            _manager.WriteMessagesToWindow();
          }
        }
        catch (Exception ex)
        {
          ExceptionHandler.HandleException(ex);
        }
      }
    }

    private void writeLoggingEnabledMessage()
    {
      DateTime now = DateTime.Now;

      var msg = new LogMessage();
      msg.TimeStamp = now;
      msg.Message = string.Format("{0} Logging enabled", now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture));

      _manager.AddMessage(msg);

      _manager.WriteMessagesToWindow();
    }

    private void writeLoggingDisabledMessage()
    {
      DateTime now = DateTime.Now;

      var msg = new LogMessage();
      msg.TimeStamp = now;
      msg.Message = string.Format("{0} Logging disabled", now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture));

      _manager.AddMessage(msg);

      _manager.WriteMessagesToWindow();
    }

    public void Enable()
    {
      writeLoggingEnabledMessage();
    }

    public void Disable()
    {
      writeLoggingDisabledMessage();
    }
  }
}
